package benchmarkapplication;

import database.DatabasePool;
import java.util.logging.Level;
import java.util.logging.Logger;

class BenchmarkApp {

    public BenchmarkApp() {
    }

    public void Run(int threadCount) {
        DatabasePool databasePool = new DatabasePool(threadCount);
        QuerySetPool queryPool = new QuerySetPool(databasePool);

        if (!queryPool.ReadFromFile("src/files/query.txt")) {
            return;
        }

        // create instances of test classes
        ThreadTest[] threadTests = new ThreadTest[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threadTests[i] = new ThreadTest(i, queryPool.GetQuerySet(i), queryPool);
        }

        // create instances of Thread class
        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(threadTests[i]);
        }

        StopWatch sw = new StopWatch();
        sw.start();

        // start all test threads
        for (int i = 0; i < threadCount; i++) {
            threads[i].start();
        }

        // Spin for a while waiting for the started thread to become alive:
        for (int i = 0; i < threadCount; i++) {
            while (!threads[i].isAlive());
            //System.err.println("Thread "+i+" is alive");
        }

        // Wait until oThread finishes. Join also has overloads
        // that take a millisecond interval or a TimeSpan object.
       // System.err.println("jsem tady !!");
        for (int i = 0; i < threadCount; i++) {
            try {
                threads[i].join();
                //System.err.println(" ............"+i+" OK .......");
            } catch (InterruptedException ex) {
                Logger.getLogger(BenchmarkApp.class.getName()).log(Level.SEVERE, null, ex);
                System.err.println(ex.toString());
            }
        }

        String executionTimeTaken = String.format("\nTime: " + sw.getElapsedTimeSecs() + "s\n");
        System.out.println(executionTimeTaken);
        databasePool.Close();

        System.out.println("Done.");
    }
}